package com.example.cupid.controller;

import com.example.cupid.pojo.Order;
import com.example.cupid.pojo.User;
import com.example.cupid.pojo.Wechat;
import com.example.cupid.service.Impl.PayServiceImpl;
import com.example.cupid.service.OrderService;
import com.example.cupid.service.PayService;
import com.example.cupid.service.WechatService;
import com.example.cupid.util.Verification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 2021/9/6
 * 支付Controller
 **/
@RestController
@RequestMapping("/pay")
public class PayController {
    //注入接口 不要注入实现类 人傻了
    @Autowired
    private PayService payService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private WechatService wechatService;

    /**
     * 下单支付
     */
    @PostMapping(value = "/confirm",produces = {"text/html;charset=UTF-8"})
    public Object pay(Wechat wechat, HttpServletRequest request)throws Exception{
        HttpSession session = request.getSession();
        User loginUser =(User) session.getAttribute("loginUser");
        String msg = loginUser.getId()+wechat.toString();
        return payService.savePay(msg);
    }

    @PostMapping("/notify")
    public void notifyAsyn(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        Map<String, String[]> map = request.getParameterMap();
        String status = map.get("trade_status")[0];
        System.out.println(status);
        if(status.equals("TRADE_SUCCESS")){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date gmt_create = sdf.parse(map.get("gmt_create")[0]);
            Date gmt_payment = sdf.parse(map.get("gmt_payment")[0]);
            BigDecimal total_amount = new BigDecimal(map.get("total_amount")[0]);
            String out_trade_no = map.get("out_trade_no")[0];
            String trade_no = map.get("trade_no")[0];
            Order order = new Order(total_amount,gmt_create,gmt_payment,out_trade_no,trade_no);
//            将订单保存到数据库
            orderService.saveOrder(order);
//            将投放的微信保存到数据库
            String passback_params = URLDecoder.decode(request.getParameter("passback_params"), "UTF-8");
            Integer userId = Integer.parseInt(passback_params.substring(0,passback_params.indexOf("W")));
            Wechat wechat = new Wechat();
            String wechatStr = passback_params.substring(passback_params.indexOf("(")+1, passback_params.indexOf(")"));
            String[] list = wechatStr.split(", ");
            for (String item : list) {
                String key = item.substring(0, item.indexOf("="));
                String value = item.substring(item.indexOf("=") + 1);
                switch (key) {
                    case "id":
                        wechat.setId(Integer.parseInt(value));
                        break;
                    case "wechat":
                        wechat.setWechat(value);
                        break;
                    case "sex":
                        wechat.setSex(Integer.parseInt(value));
                        break;
                    case "school":
                        wechat.setSchool(value);
                        break;
                    case "grade":
                        wechat.setGrade(value);
                        break;
                    default:
                        wechat.setDescription(value);
                        break;
                }
            }
            System.out.println("wechat="+wechat);
            System.out.println("userId="+userId);
            wechatService.saveWechat(wechat);
            int wechatId = wechatService.getWechat(wechat.getWechat()).getId();
            wechatService.saveUserWechatSave(userId,wechatId);
        }else{
            System.out.println("trade_status = "+status);
        }
    }
    @PostMapping(value = "/takeconfirm",produces = {"text/html;charset=UTF-8"})
    public Object takePay(int sex, HttpServletRequest request)throws Exception{
        HttpSession session = request.getSession();
        User loginUser =(User) session.getAttribute("loginUser");
        String msg =loginUser.getId() +"sex="+sex;
        return payService.takePay(msg);
    }

    @PostMapping("/takeNotify")
    public void takeNotifyAsyn(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {
        Map<String, String[]> map = request.getParameterMap();
        String status = map.get("trade_status")[0];
        System.out.println(status);
        if(status.equals("TRADE_SUCCESS")){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date gmt_create = sdf.parse(map.get("gmt_create")[0]);
            Date gmt_payment = sdf.parse(map.get("gmt_payment")[0]);
            BigDecimal total_amount = new BigDecimal(map.get("total_amount")[0]);
            String out_trade_no = map.get("out_trade_no")[0];
            String trade_no = map.get("trade_no")[0];
            Order order = new Order(total_amount,gmt_create,gmt_payment,out_trade_no,trade_no);
//          将订单保存到数据库
            orderService.saveOrder(order);
            //随即获取一个微信
            String passback_params = URLDecoder.decode(request.getParameter("passback_params"), "UTF-8");
            Integer userId = Integer.parseInt(passback_params.substring(0,passback_params.indexOf("s")));
            String sexInfo = passback_params.substring(1);
           /* System.out.println(passback_params);
            System.out.println(userId);
            System.out.println(sexInfo);*/
            String key = sexInfo.substring(0, sexInfo.indexOf("="));
            Integer value = Integer.valueOf(sexInfo.substring(sexInfo.indexOf("=") + 1));
            /*System.out.println(key);
            System.out.println(value);*/
            //已经放进去的微信
            List<Wechat> list_save = wechatService.getSaveWechatByUserId(userId);
            List<Wechat> list_take = wechatService.getTakeWechatByUserId(userId);
            //所有符合检索条件的微信
            List<Wechat> listTake = new ArrayList<>();
            listTake = wechatService.getSaveWechatBySearch(value);
            for (Wechat wechat : listTake) {
                System.out.println(wechat);
            }
            int length = listTake.size();
            System.out.println(length);
            boolean flag = true;
            while (flag){
                flag =false;
                Wechat wechat = listTake.get(Verification.secureRandom(length));
                System.out.println(wechat);
                for (Wechat wechat_save : list_save) {
                    if (wechat_save.getId() == wechat.getId())
                        flag = true;
                }
                for (Wechat wechat_take : list_take) {
                    if (wechat_take.getId() == wechat.getId())
                        flag = true;
                }
                if (!flag){
                    int wechatId = wechat.getId();
                    wechatService.takeUserWechatSave(userId,wechatId);
                }
            }
            //System.out.println(list.size());;
            //System.out.println(wechat.getWechat());
//          将获得的微信保存到数据库
        }else{
            System.out.println("trade_status = "+status);
        }
    }
}
